package com.gimi.test_jpa.com.gimi.util;

import cn.hutool.json.JSONUtil;
import com.gimi.test_jpa.com.gimi.dto.BaseDto;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BeanUtils {

    /**
     * object转Map
     *
     * @param obj
     * @param isIgnoreNull 是否忽略为空的字段
     * @return
     * @throws Exception
     */
    public static Map<String, Object> beantoMap(Object obj, Boolean isIgnoreNull) throws Exception {
        HashMap<String, Object> returnMap = new HashMap<>();
        if (obj instanceof Map) { //判断是否为map 特殊处理
            if (!isIgnoreNull) {
                return (Map<String, Object>) obj;
            }
            Map objMap = (Map) obj;
            Set set = objMap.keySet();
            set.forEach(str -> {  //遍历obj
                returnMap.put(str.toString(), "".equals(objMap.get(str.toString())) ? null : objMap.get(str.toString()));
            });
            return returnMap;
        }
        //obj不是map，则需要反射处理
        Class<?> aClass = obj.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (isIgnoreNull) { //忽略掉为空或空字符串的字段
                returnMap.put(field.getName(), "".equals(field.get(obj)) ? null : field.get(obj));
            } else {  //不忽略
                //map的value不能为null，所以需要处理成空字符串
                returnMap.put(field.getName(), (field.get(obj) == null || "".equals(field.get(obj))) ? "" : field.get(obj));
            }
        }
        return returnMap;
    }

    /**
     * object转Map
     * 默认不忽略为空的字段
     *
     * @param obj
     * @return
     * @throws Exception
     */
    public static Map<String, Object> beantoMap(Object obj) throws Exception {
        return beantoMap(obj, false);
    }

    public static void main(String[] args) throws Exception {
        BaseDto baseDto = new BaseDto();
        baseDto.setAcountType("aaaa");
        baseDto.setOrgCode("");
        baseDto.setUpdateTime(new Date());

        HashMap<String, Object> objectHashMap = new HashMap<>();
        objectHashMap.put("a", "aaa");
        objectHashMap.put("b", "");

        Map<String, Object> map = BeanUtils.beantoMap(baseDto, true);
        System.out.println(JSONUtil.toJsonStr(map));
    }
}
